package com.zy.yun.controller.sys;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zy.yun.base.annotation.NotNullPara;
import com.zy.yun.base.common.DataTable;
import com.zy.yun.base.common.RestResult;
import com.zy.yun.base.constant.StatusEnum;
import com.zy.yun.base.entity.User;
import com.zy.yun.base.entity.dto.UserDTO;
import com.zy.yun.base.entity.vo.UserVO;
import com.zy.yun.controller.common.BaseController;
import com.zy.yun.provider.service.IUserService;
import com.zy.yun.utils.DataFilterUtil;
import com.zy.yun.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 王彦委
 * @since 2019-09-12
 */
@Api(description = "用户管理", tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<User, UserVO> {


    @Autowired
    private IUserService userService;
    @Autowired
    private RedisUtil<User,List> redisUtil;
    @Autowired
    private DataFilterUtil dataFilterUtil;

    /**
     * @Author 王彦委
     * @Description: 用户列表
     * @Date: 22:16 2019/10/16
     */

    @ApiOperation(value = "用户列表")
    @PostMapping("findPage")
    public DataTable findPage(HttpServletRequest request,UserDTO user, @RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "30") Integer pageSize) {

        EntityWrapper<User> userQueryWrapper = new EntityWrapper<>();

        //设置 数据过滤
        dataFilterUtil.setDataFilter(request,userQueryWrapper);

        //根据姓名查询
        if (StringUtils.isNotBlank(user.getName())) {
            userQueryWrapper.like("name", user.getName());
        }

        return findPage(userQueryWrapper, pageNum, pageSize);
    }

    /**
     * @Author 王彦委
     * @Description: 增加用户
     * @Date: 23:09 2019/10/17
     */
    @ApiOperation(value = "增加用户")
    @PostMapping("save")
    @NotNullPara({"name", "password"})
    public RestResult save(UserDTO user) {

        if (StringUtils.isNotBlank(user.getNote()) && user.getNote().length() > 50) {
            return RestResult.buildError("备注最多50个字！");
        }

        //用户名不能重复
        EntityWrapper<User> userQueryWrapper = new EntityWrapper<>();
        userQueryWrapper.eq("name", user.getName());
        if (StringUtils.isNotBlank(user.getPhone())) {
            userQueryWrapper.eq("phone", user.getPhone());
        }
        userQueryWrapper.eq("name", user.getName());

        User oldUser = userService.selectOne(userQueryWrapper);
        //验证是手机号还是用户名重复
        if (null != oldUser) {
            if (user.getName().equalsIgnoreCase(oldUser.getName())) {
                return RestResult.buildError("用户名已经存在！");
            }
            return RestResult.buildError("手机号已经存在！");
        }

        //盐
//        String salt = UUID.randomUUID().toString();
//        String newPassword = Md5Utils.md5salt(user.getPassword(), salt);
//        user.setSalt(salt);

        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.setCreateTime(new Date());
        user.setStatus(StatusEnum.STATUS_START.getCode());

        if (userService.insert(user)) {
            return RestResult.buildSuccess();
        }
        return RestResult.buildError();
    }

    /**
     * @Author: 王彦委
     * @Description: 重置密码
     * @Date: 10:28 2019/10/20
     */
    @PostMapping("userResetPassword")
    @ApiOperation(value = "重置用户密码")
    @NotNullPara({"ids"})
    public RestResult userResetPassword(@RequestParam(value = "ids") List<Long> ids) {

        //默认密码123456
//        String salt = UUID.randomUUID().toString();
//        String newPassword = Md5Utils.md5salt("123456", salt);
        String newPassword =new BCryptPasswordEncoder().encode("123456");
        EntityWrapper<User> userQueryWrapper = new EntityWrapper<>();
        userQueryWrapper.in("id", ids);
        User user = new User();
        user.setPassword(newPassword);
//        user.setSalt(salt);
        if (userService.update(user, userQueryWrapper)) {
            return RestResult.buildSuccess();
        }

        return RestResult.buildError();
    }

    /**
     * @Author: 王彦委
     * @Description: 修改
     * @Date: 21:07 2019/10/21
     */
    @PostMapping("update")
    @ApiOperation("修改用户")
    public RestResult update(UserDTO user) {
        if (StringUtils.isNotBlank(user.getNote()) && user.getNote().length() > 50) {
            return RestResult.buildError("备注最多50个字！");
        }

        //用户名不能重复
        EntityWrapper<User> userQueryWrapper = new EntityWrapper<>();

        if (StringUtils.isNotBlank(user.getPhone())) {
            userQueryWrapper.eq("name",user.getName());
        } else {
            userQueryWrapper.eq("name", user.getName());
        }
        //排除自己
        userQueryWrapper.ne("id", user.getId());

        List<User> oldUsers = userService.selectList(userQueryWrapper);
        //验证是手机号还是用户名重复
        if (CollectionUtils.isNotEmpty(oldUsers)) {
            if (user.getName().equalsIgnoreCase(oldUsers.get(0).getName())) {
                return RestResult.buildError("用户名已经存在！");
            }
            return RestResult.buildError("手机号已经存在！");
        }

        //盐
        if (StringUtils.isNotBlank(user.getPassword())) {
//            String salt = UUID.randomUUID().toString();
//            String newPassword = Md5Utils.md5salt(user.getPassword(), salt);
            String newPassword = new BCryptPasswordEncoder().encode(user.getPassword());
//            user.setSalt(salt);
            user.setPassword(newPassword);
        }else {
            user.setPassword(null);
        }

        if (userService.updateById(user)) {
            return RestResult.buildSuccess();
        }
        return RestResult.buildError();
    }

}
